package cn.edu.jlu.community.app.post;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.edu.jlu.community.R;
import cn.edu.jlu.community.server.AppServer;
import cn.edu.jlu.community.util.ToastUtil;


public class CommentAdapter extends BaseAdapter {

    private Context mContext;
    private List<AVObject> mDataSet;

    public CommentAdapter(Context context, List<AVObject> dataSet) {
        mContext = context;
        mDataSet = dataSet;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView != null) {
            holder = (ViewHolder) convertView.getTag();
        } else {
            convertView = LayoutInflater.from(mContext)
                    .inflate(R.layout.post_comment_list_item, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }

        AVObject data = mDataSet.get(position);
        holder.comment.setText(data.getString("content"));
        holder.author.setText(((AVUser) data.get("from")).getUsername());
        DateFormat formatter = SimpleDateFormat.getDateTimeInstance();
        holder.time.setText(formatter.format(data.getUpdatedAt()));

        String id = ((AVUser) data.get("from")).getObjectId();
        AppServer.loadPortrait(id, new PortraitCallback(holder.portrait));

        return convertView;
    }

    private class PortraitCallback implements AppServer.LoaderCallback {
        private ImageView mPortrait;

        PortraitCallback(ImageView imageView) {
            mPortrait = imageView;
        }

        @Override
        public void onFinish(final Object data) {
            mPortrait.setImageBitmap((Bitmap) data);
        }

        @Override
        public void onError(AVException e) {

        }
    }

    static class ViewHolder {
        @InjectView(R.id.portrait)
        ImageView portrait;
        @InjectView(R.id.comment_text)
        TextView comment;
        @InjectView(R.id.comment_time)
        TextView time;
        @InjectView(R.id.comment_author)
        TextView author;

        public ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    @Override
    public int getCount() {
        return mDataSet.size();
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }
}
